package vip.xiaonuo.facedoor.modular.deviceoperation.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jodd.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.service.DeviceBaseService;
import vip.xiaonuo.facedoor.modular.deviceoperation.entity.DeviceOperation;
import vip.xiaonuo.facedoor.modular.deviceoperation.param.AppUploadParam;
import vip.xiaonuo.sys.modular.file.enums.FileTypeEnum;
import vip.xiaonuo.sys.modular.file.service.SysFileInfoService;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AppFileService {

    @Resource
    private SysFileInfoService sysFileInfoService;

    @Resource
    private DeviceOperationService operationService;

    @Resource
    private DeviceBaseService deviceBaseService;

    public void uploadFile( AppUploadParam param) {
        if(ObjectUtil.isEmpty(param) || StringUtil.isEmpty(param.getDeviceNo())){
            throw new ServiceException(1,"设备编号未上传");
        }

        // 判断设备编号是否存在
        List<DeviceBase> devices = deviceBaseService.list(new LambdaQueryWrapper<DeviceBase>()
                .eq(DeviceBase :: getRegistrationCode , param.getDeviceNo()));

        if( devices.isEmpty()){
            throw new ServiceException(2,"设备编号不存在");
        }

        Long fileId = sysFileInfoService.uploadFile(param.getFile(), FileTypeEnum.APP_UPLOAD);
        DeviceOperation operation = new DeviceOperation();
        operation.setDeviceId(devices.get(0).getId());
        operation.setOperateFile(fileId);
        operationService.save(operation);
    }
}
